#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_libxml2_fun_003.py
@Time:      2024/02/22 11:12:50
@Author:    hongfeng
@Version:   1.0
@Contact:   wb-zhf668260@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    hongfeng
"""

import os
from common.basetest import LocalTest
class Test(LocalTest):
    """
    See tc_libxml2_fun_003.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "libxml2-devel"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > modify_xml.c <<EOF
#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/tree.h>

int main() {
    xmlDocPtr doc = NULL;
    xmlNodePtr root_node = NULL, child_node = NULL;

    // 初始化libxml2
    xmlInitParser();

    // 加载已存在的XML文档
    doc = xmlReadFile("test_003.xml", NULL, 0);
    if (doc == NULL) {
        fprintf(stderr, "Error parsing file\\n");
        return 1;
    }

    // 获取根节点
    root_node = xmlDocGetRootElement(doc);
    if (root_node == NULL) {
        fprintf(stderr, "Error getting root element\\n");
        xmlFreeDoc(doc);
        return 1;
    }

    // 查找要修改的子节点（例如，查找名为"body"的第一个子节点）
    child_node = root_node->children;
    while (child_node != NULL) {
        if (xmlStrcmp(child_node->name, BAD_CAST "body") == 0) {
            xmlNodeSetContent(child_node, BAD_CAST "Modified Content");
            break;
        }
        child_node = child_node->next;
    }

    // 保存修改后的XML文档到文件
    int result = xmlSaveFormatFileEnc("modified.xml", doc, "UTF-8", 1);
    if (result < 0) {
        fprintf(stderr, "Error saving XML to file\\n");
    }

    // 清理并释放资源
    xmlFreeDoc(doc);
    xmlCleanupParser();

    return 0;
}
"""
        self.cmd(cmdline)
        self.cmd("gcc -o modify_xml modify_xml.c `xml2-config --cflags --libs`")
        file_dir = os.path.dirname(__file__)
        self.cmd(f"cp {file_dir}/test.xml ./test_003.xml")

    def test(self):
        self.cmd("./modify_xml")
        ret_c,ret_o = self.cmd("cat modified.xml")
        self.assertTrue("<body>Modified Content</body>" in ret_o, 'check output error.')
        
    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm modify_xml.c modify_xml test_003.xml modified.xml")
